package cn.gdcp.listviewtest;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
   private List<Student> studentList=new ArrayList<>();
    StudentAdapter adapter;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
             initStudents();
              adapter=new StudentAdapter(MainActivity.this,R.layout.student_item,studentList);
          ListView listView=(ListView)findViewById(R.id.listview);
           listView.setAdapter(adapter);
          Button addBtn=(Button)findViewById(R.id.add);
          addBtn.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  Intent intent=new Intent(MainActivity.this,AddActivity.class);
                  startActivityForResult(intent,100);

              }
          });
          listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                  Button deleteBtn=(Button)findViewById(R.id.delete);
                  deleteBtn.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          Student student=studentList.get(position);
                          studentList.remove(student);
                          adapter.notifyDataSetChanged();
                      }
                  });
              }
          });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          if (requestCode==100&&resultCode==200){
           String name=data.getStringExtra("NAME");
              int age=data.getIntExtra("AGE",0);
              int imgId=data.getIntExtra("IMGID",R.drawable.icon);
              Student addstudent=new Student(name,age,imgId);
              studentList.add(addstudent);
              adapter.notifyDataSetChanged();
          }
    }

    private void initStudents() {
        Student student1=new Student("A",11, R.drawable.icon);
          studentList.add(student1);
        Student student2=new Student("A",12, R.drawable.icon);
        studentList.add(student2);
        Student student3=new Student("A",13, R.drawable.icon);
        studentList.add(student3);
        Student student4=new Student("A",14, R.drawable.icon);
        studentList.add(student4);
        Student student5=new Student("A",15, R.drawable.icon);
        studentList.add(student5);

    }
}
